package com.ladlee.util;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.ladlee.constant.CommonConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;

import java.util.Base64;
import java.util.List;

/**
 * @Auther: dingchang
 * @Date: 2018/12/15 16:57
 * @Description: 用户相关的工具类
 */
@Slf4j
public class UserUtils {

    //用于解决 “在使用线程池等会缓存线程的组件情况下传递ThreadLocal” 问题的
    private static final ThreadLocal<String> THREAD_LOCAL_USER = new TransmittableThreadLocal<>();

    private static final String KEY_USER = "user";

    /**
     * 根据请求heard中的token获取用户角色
     * @param request
     * @return
     */
    public static List<String> getRole(HttpServletRequest request){
        String token = getToken(request);
        String key = Base64.getEncoder().encodeToString(CommonConstant.SIGN_KEY.getBytes());
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        List<String> roleNames = (List<String>) claims.get("authorities");
        return roleNames;
    }

    /**
     * 根据header中的token获取用户ID
     *
     * @param httpServletRequest
     * @return 用户ID
     */
    public static Integer getUserId(javax.servlet.http.HttpServletRequest httpServletRequest) {
        String token = getToken(httpServletRequest);
        String key = Base64.getEncoder().encodeToString(CommonConstant.SIGN_KEY.getBytes());
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        Integer userId = (Integer) claims.get("userId");
        return userId;
    }

    /**
     * 获取请求中token
     *
     * @param httpServletRequest request
     * @return token
     */
    public static String getToken(javax.servlet.http.HttpServletRequest httpServletRequest) {
        String authorization = httpServletRequest.getHeader(CommonConstant.REQ_HEADER);
        return StringUtils.substringAfter(authorization, CommonConstant.TOKEN_SPLIT);
    }

    //设置用户信息
    public static void serUser(String username){
        THREAD_LOCAL_USER.set(username);
        MDC.put(KEY_USER,username);
    }

    //从threadlocal 获取用户名
    public static String getUser() {
        return THREAD_LOCAL_USER.get();
    }
    public static void clearAllUserInfo() {
        THREAD_LOCAL_USER.remove();
        MDC.remove(KEY_USER);
    }

}
